package com.mky.mkcompany.authorization.manager.impl;

import com.mky.mkcompany.authorization.manager.TokenManager;
import com.mky.mkcompany.authorization.model.TokenModel;
import com.mky.mkcompany.dic.SecurityDic;
import com.mky.mkcompany.dic.UserLoginDic;
import com.mky.mkcompany.tool.EncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 通过Redis存储和验证token的实现类
 */
@Component
public class RedisTokenManager implements TokenManager {
    private final Logger LOGGER = LoggerFactory.getLogger(getClass());
    @Autowired
    private RedisTemplate<String, String> redis;

//    @Autowired
//    public void setRedis(RedisTemplate<BigInteger, String> redis) {
//        this.redis = redis;
//        //泛型设置成Long后必须更改对应的序列化方案
//        redis.setKeySerializer(new JdkSerializationRedisSerializer());
//    }

    public TokenModel createToken(String userId,String username) {
       // String oldToken = redis.boundValueOps(UserLoginDic.PROJ_NAME+userId).get();
        TokenModel model=null;
//        if (oldToken != null) {
//            LOGGER.info("username="+username+"的用户重新登录了");
//            model = new TokenModel(userId, oldToken);
//        }else{
            //使用uuid作为源token
            String token = UUID.randomUUID().toString().replace("-", "");
            model = new TokenModel(userId, token);
            //存储到redis并设置过期时间
            redis.boundValueOps(UserLoginDic.PROJ_NAME+userId).set(token, SecurityDic.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
       // }
        return model;
    }

    public TokenModel getToken(String authentication) {
        if (authentication == null || authentication.length() == 0) {
            return null;
        }
//        try {
//            authentication = EncryptUtil.decrypt(authentication);
//        }catch (Exception e){
//            LOGGER.error("解密出错，详情:"+e.getMessage(),e);
//        }
        String[] param = authentication.split("_");
        if (param.length != 2) {
            return null;
        }
        //使用userId和源token简单拼接成的token，可以增加加密措施
        String userId =param[0];
        String token = param[1];
        return new TokenModel(userId, token);
    }

    public boolean checkToken(TokenModel model) {
        if (model == null) {
            return false;
        }
        String token = redis.boundValueOps(UserLoginDic.PROJ_NAME+model.getUserId()).get();
        if (token == null || !token.equals(model.getToken())) {
            return false;
        }
        //如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间
        //redis.boundValueOps(model.getUserId()).expire(SecurityDic.TOKEN_ADD_EXPIRES_HOUR, TimeUnit.HOURS);
        return true;
    }

    public void deleteToken(String userId) {
        redis.delete(UserLoginDic.PROJ_NAME+userId);
    }
}
